<script setup>
import api from '../api/userProduct_api.js'
import { ref, onMounted, computed } from "vue";
import { ElMessageBox, ElPagination, ElTable, ElTableColumn, ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElPopover, ElTag, ElAvatar, ElIcon, ElSelect, ElOption } from 'element-plus';
import lodash from 'lodash'
import productAPI from '../api/product_api.js'
import userAPI from '../api/user_api.js'

// 表格数据
const tableData = ref([])
const total = ref(0);
// 弹窗显隐
const editWinVisible = ref(false);
const addWinVisible = ref(false);
// 查询条件
const searchObj = ref({
  current: 1,
  limit: 10,
  user_id: '',
  product_id: '',
  up_price: '',
  remarks: ''
});
// 新增/编辑对象
const obj = ref({});
// 下拉数据源
const products = ref([]);
const users = ref([]);

// 页面初始化
onMounted(async () => {
  await Promise.all([search(), loadProducts(), loadUsers()])
})

// 通用查询
const search = async () => {
  const result = await api.page(searchObj.value);
  // 过滤掉返回数据中的deleted字段，不显示但保留删除功能
  tableData.value = result.data.map(item => {
    const { deleted, ...rest } = item;
    return rest;
  });
  total.value = result.count;
}

// 加载商品下拉
const loadProducts = async () => {
  const result = await productAPI.page({ current: 1, limit: 100 });
  products.value = result.data || [];
}

// 加载用户下拉
const loadUsers = async () => {
  const result = await userAPI.page({ current: 1, limit: 100 });
  users.value = result.data || [];
}

// 分页处理
const handleSizeChange = () => search()
const handleCurrentChange = () => search()

// 查询按钮
const handlerSearch = async () => {
  searchObj.value.current = 1;
  await search();
}

// 编辑弹窗 - 取消
const editCancel = () => {
  obj.value = {};
  editWinVisible.value = false;
}

// 编辑弹窗 - 提交
const editCommit = async () => {
  // 确保提交数据中无deleted字段
  const { deleted, ...submitData } = obj.value;
  await api.edit(submitData);
  await search();
  editWinVisible.value = false;
}

// 新增弹窗 - 取消
const addCancel = () => {
  obj.value = {};
  addWinVisible.value = false;
}

// 新增弹窗 - 提交
const addCommit = async () => {
  // 确保提交数据中无deleted字段
  const { deleted, ...submitData } = obj.value;
  await api.add(submitData);
  await search();
  addWinVisible.value = false;
  obj.value = {};
}

// 打开新增弹窗
const handleAdd = async () => {
  obj.value = {};
  await Promise.all([loadProducts(), loadUsers()]);
  addWinVisible.value = true;
}

// 打开编辑弹窗（过滤deleted字段）
const handleEdit = async (index, row) => {
  const { deleted, ...rowWithoutDeleted } = row;
  obj.value = lodash.clone(rowWithoutDeleted);
  await Promise.all([loadProducts(), loadUsers()]);
  editWinVisible.value = true;
}

// 删除操作（保留功能）
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗？',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async () => {
        await api.del(row.id);
        searchObj.value.current = 1;
        await search();
      })
      .catch(() => {})
}

// 表单显示的用户名称
const formUserName = computed(() => {
  return users.value.find(item => item.id === obj.value.user_id)?.name || ''
})

// 表单显示的商品名称
const formProductName = computed(() => {
  return products.value.find(item => item.id === obj.value.product_id)?.name || ''
})
</script>

<template>
  <!-- 查询表单 -->
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px ">
    <el-form-item label="用户ID">
      <el-input v-model="searchObj.user_id" placeholder="请输入用户ID" clearable />
    </el-form-item>
    <el-form-item label="商品ID">
      <el-input v-model="searchObj.product_id" placeholder="请输入商品ID" clearable />
    </el-form-item>
    <el-form-item label="价格">
      <el-input v-model="searchObj.up_price" placeholder="请输入价格" clearable />
    </el-form-item>
    <el-form-item label="备注">
      <el-input v-model="searchObj.remarks" placeholder="请输入备注" clearable />
    </el-form-item>
  </el-form>

  <!-- 操作按钮 -->
  <el-form :inline="true">
    <el-form-item>
      <el-button type="primary" @click="handlerSearch">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </el-form-item>
  </el-form>

  <!-- 数据表格（移除删除状态列） -->
  <el-table :data="tableData" style="width: 100%">
    <el-table-column label="ID" width="80">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>id: {{ scope.row.id }}</div>
          </template>
          <template #reference>
            <el-tag>{{ scope.row.id }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column label="用户ID" width="100">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>user_id: {{ scope.row.user_id }}</div>
          </template>
          <template #reference>
            <el-tag type="info">{{ scope.row.user_id }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column label="用户" width="120">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>user: {{ users.find(u => u.id === scope.row.user_id)?.name }}</div>
          </template>
          <template #reference>
            <el-tag>{{ users.find(u => u.id === scope.row.user_id)?.name }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column label="商品ID" width="100">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>product_id: {{ scope.row.product_id }}</div>
          </template>
          <template #reference>
            <el-tag type="info">{{ scope.row.product_id }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column label="商品" width="180">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>product: {{ products.find(p => p.id === scope.row.product_id)?.name }}</div>
          </template>
          <template #reference>
            <el-tag>{{ products.find(p => p.id === scope.row.product_id)?.name }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column label="更新日期" width="180">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>up_date: {{ scope.row.up_date }}</div>
          </template>
          <template #reference>
            <el-tag>{{ scope.row.up_date }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column label="备注" width="200">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>remarks: {{ scope.row.remarks }}</div>
          </template>
          <template #reference>
            <el-tag>{{ scope.row.remarks }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页组件 -->
  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.limit"
      :page-sizes="[10, 20, 30, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />

  <!-- 编辑弹窗 -->
  <el-dialog v-model="editWinVisible" title="编辑" width="500">
    <el-form :model="obj">
      <el-form-item label="用户" :label-width="100">
        <el-select v-model="obj.user_id" placeholder="请选择用户" style="width: 240px">
          <el-option
              v-for="item in users"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          ></el-option>
        </el-select>
        <div style="margin-top:8px;color:#999">当前选择：{{ formUserName }}</div>
      </el-form-item>
      <el-form-item label="商品" :label-width="100">
        <el-select v-model="obj.product_id" placeholder="请选择商品" style="width: 240px">
          <el-option
              v-for="item in products"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          ></el-option>
        </el-select>
        <div style="margin-top:8px;color:#999">当前选择：{{ formProductName }}</div>
      </el-form-item>
      <el-form-item label="更新日期" :label-width="100">
        <el-input v-model="obj.up_date" autocomplete="off" />
      </el-form-item>
      <el-form-item label="价格" :label-width="100">
        <el-input v-model="obj.up_price" autocomplete="off" />
      </el-form-item>
      <el-form-item label="备注" :label-width="100">
        <el-input v-model="obj.remarks" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit">提交</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 新增弹窗 -->
  <el-dialog v-model="addWinVisible" title="新增" width="500">
    <el-form :model="obj">
      <el-form-item label="用户" :label-width="100">
        <el-select v-model="obj.user_id" placeholder="请选择用户" style="width: 240px">
          <el-option
              v-for="item in users"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品" :label-width="100">
        <el-select v-model="obj.product_id" placeholder="请选择商品" style="width: 240px">
          <el-option
              v-for="item in products"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="更新日期" :label-width="100">
        <el-input v-model="obj.up_date" autocomplete="off" />
      </el-form-item>
      <el-form-item label="价格" :label-width="100">
        <el-input v-model="obj.up_price" autocomplete="off" />
      </el-form-item>
      <el-form-item label="备注" :label-width="100">
        <el-input v-model="obj.remarks" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addCancel">取消</el-button>
        <el-button type="primary" @click="addCommit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-table {
  margin-top: 10px;
}
</style>
